import sys
from os import walk
from zipfile import ZipFile
from Tkinter import Tk, YES, BOTH
from TreeWidget import TreeItem, TreeNode, ScrolledCanvas

class EggTree(TreeItem):
   db = {}
   @classmethod
   def _search4eggs(cls, root):
      for root, dirs, files in walk(root):
         for e in [egg for egg in files if egg.endswith('.egg')]:
            cls.db.setdefault(root, set()).add(e)
   @classmethod
   def init(cls):
      for p in sys.path:
         cls._search4eggs(p)
      cls._search4eggs('.')
   def __init__(self, path='',parent=''):
      TreeItem.__init__(self)
      self.path = path
      self.parent=parent
   def IsExpandable(self):
      return not self.parent.startswith('EGG:')
   def GetText(self):
      return self.path if self.path else 'Eggs...'
   def GetIconName(self):
      if not self.IsExpandable():
         return "python" if self.path.endswith('.py') else 'file' 
   def GetSubList(self):
      if self.path.endswith('.egg'):
         parent='EGG:%s/%s' % (self.parent, self.path)
         names = ZipFile(self.parent+'/'+self.path).namelist()
         result = [f for f in names if not f.startswith('EGG-INFO/') and not f.endswith('.pyc')] 
      elif self.path:
         parent = self.path
         result = sorted(list(self.db[self.path]))
      else:
         parent=''
         result = sorted(self.db.keys())
      return [EggTree(p, parent) for p in result]
   def OnDoubleClick(self):
      if not self.parent.startswith('EGG:'):
         return
      print ZipFile(self.parent[4:]).read(self.path)

class Main(Tk):
   def __init__(self):
      Tk.__init__(self)
      self.title('egggui.py')
      sc = ScrolledCanvas(self, bg="white", highlightthickness=0, takefocus=True)
      sc.frame.pack(expand=YES, fill=BOTH)
      EggTree.init()
      TreeNode(sc.canvas, None, EggTree()).expand()
      self.mainloop()
      
Main()
